﻿@model NWNT.Web.Models.UserInfoModel
@{
    ViewBag.Title = "User Profile";
}

<h1>@ViewBag.Title</h1>
<!-- form start -->
<div>
    @*<pre data-bind="text: ko.toJSON($root.user(), null, 2)"></pre>*@
    @*<div>Corporate Employee Management</div>
        <div>Relationship Information Section</div>*@


    <!-- Nav tabs -->
    <ul class="nav nav-tabs" role="tablist">
        <li class="active"><a href="#Profile" role="tab" data-toggle="tab">Profile</a></li>
        <li><a href="#Stress" role="tab" data-toggle="tab">Stress-o-meter Information</a></li>
    </ul>
    <!-- Tab panes -->
    <div class="tab-content">
        <div class="tab-pane active" id="Profile">
            <div class="form-horizontal">
                <div class="form-group">
                    <label class="col-md-3 control-label">Relationship No.</label>
                    <div class="col-md-9">
                        <input type="text" class="form-control" data-bind="value:$root.user().RelationshipCode" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-3 control-label">Company</label>
                    <div class="col-md-9">
                        <p class="form-control-static" data-bind="text:$root.user().CompanyName"></p>
                    </div>
                </div>
            </div>
            <h4>Personel Information Section</h4>
            <div class="form-horizontal">
                <div class="form-group">
                    <label class="col-md-3 control-label">Prefix</label>
                    <div class="col-md-9">
                        <select class="form-control" data-bind="options:$root.prefixes,optionsText:'PrefixCode',optionsValue:'PrefixId',value: $root.user().PrefixId,
                       optionsCaption: 'Choose Prefix'">
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-3 control-label">First Name*</label>
                    <div class="col-md-9">
                        <input type="text" class="form-control" data-bind="value:$root.user().FirstName" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-3 control-label">Middle Name</label>
                    <div class="col-md-9">
                        <input type="text" class="form-control" data-bind="value:$root.user().MiddleName" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-3 control-label">Last Name*</label>
                    <div class="col-md-9">
                        <input type="text" class="form-control" data-bind="value:$root.user().LastName" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-3 control-label">Date Of Birth*</label>
                    <div class="col-md-9">
                        <input type="text" class="form-control" id="txtDOB" readonly="readonly" data-bind="value:($root.user().DateOfBirth === null ? '' : moment($root.user().DateOfBirth).format('DD-MMM-YYYY'))" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-3 control-label">Gender</label>
                    <div class="col-md-9">
                        <input type="radio" name="Gender" value="M" data-bind="checked:$root.user().Gender" />Male
                        <input type="radio" name="Gender" value="F" data-bind="checked:$root.user().Gender" />Female
                    </div>
                </div>
            </div>
            <div>
                <h4 class="mg-top50">Add New Address <a title="Add New Address" href="javascript:void(0);" data-bind="click:addAddress"><span title="Add New Address" class="glyphicon glyphicon-plus"></span></a></h4>
                <!-- ko foreach: $root.user().UserProfiles-->
                <div class="form-horizontal">
                    <div class="row">
                        <label class="col-md-3 control-label">&nbsp;</label>
                        <div class="col-md-9">
                            <h3>Address<span data-bind="text:$data.Counter"></span> <a href="javascript:void(0);" data-bind="click:$root.deleteAddress" title="Delete"><span title="Delete" class="glyphicon glyphicon-trash"></span></a></h3>
                        </div>
                    </div>
                    <hr class="mg-topnone" />
                    <div class="form-group">
                        <label class="col-md-3 control-label">Address #1</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" data-bind="value:$data.Address1" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">Address #2</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" data-bind="value:$data.Address2" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">Mobile No*</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" data-bind="value:$data.MobileNo" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">Phone</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" data-bind="value:$data.PhoneNo" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">City*</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" data-bind="value:$data.City" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">Email*</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" data-bind="value:$data.Email" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">Pincode</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" data-bind="value:$data.Pincode" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">Fax</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" data-bind="value:$data.Fax" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">Country</label>
                        <div class="col-md-9">
                            <select class="form-control" data-bind="options:$root.countries,optionsText:'CountryCode',optionsValue:'CountryId',value: $data.CountryId,
                       optionsCaption: 'Choose Country',event:{change:$root.onCountryChange}">
                            </select>
                            @*<input type="text" class="form-control" data-bind="value:$data.CountryId" />*@
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">Website</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control" data-bind="value:$data.Website" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">State</label>
                        <div class="col-md-9">
                            <select class="form-control" data-bind="options:$data.states,optionsText:'StateCode',optionsValue:'StateId',value: $data.StateId,
                       optionsCaption: 'Choose State'">
                            </select>
                            @*<input type="text" class="form-control" data-bind="value:$data.StateId" />*@
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label">Applicable Stress-O-Meter</label>
                        <div class="col-md-9">
                            <input type="radio" value="A" data-bind="checked:$data.ApplicableStressOMeter,attr:{'name':'ApplStressOMeter'+$data.Counter}" />Adult
                            <input type="radio" value="S" data-bind="checked:$data.ApplicableStressOMeter,attr:{'name':'ApplStressOMeter'+$data.Counter}" />Student
                            @*<input type="text" class="form-control" data-bind="value:$root.user().ApplicableStressOMeter" />*@
                        </div>
                    </div>
                </div>
                <!-- /ko -->
            </div>
        </div>
        <div class="tab-pane" id="Stress">
            <h4>Stress test date</h4>
            <div class="form-horizontal">

                <!-- ko foreach: $root.user().StressResults-->
                <div class="form-group">
                    @*<label class="col-md-2 control-label">Company</label>*@
                    <div class="col-md-10"><a href="javascript:void(0)" target="_blank" data-bind="text:moment($data.StressDate).format('DD-MMM-YYYY'),attr:{href:('StressResult?stressResultId='+$data.StressResultId)}"></a></div>
                </div>
                <!-- /ko -->
            </div>
        </div>
    </div>
    <!-- tab pane end-->
    <div class="mg-top20">
        <button class="btn btn-primary" type="submit" id="Submit" data-bind="click:save">Submit</button>
        @*<input type="button" value="Submit" name="Submit" data-bind="click:save" />*@
    </div>
</div>
<!-- form end-->
<script type="text/javascript">
    var data = [@Html.Raw(Json.Encode(Model))];
    var prefixes = [@Html.Raw(Json.Encode(ViewBag.Prefixes))];
    @*var states = [@Html.Raw(Json.Encode(ViewBag.States))];*@
    var countries = [@Html.Raw(Json.Encode(ViewBag.Countries))];

    states = [];// states[0];
    countries = countries[0];
    prefixes = prefixes[0];
    data = data[0];
    var errorMessages = [],
        validationMessage = '';

    function UserProfileModel(user) {
        $(function () {
            $("#txtDOB").datepicker({
                showOn: "button",
                buttonImage: "../../Content/Default/Images/ico_search.png",
                buttonImageOnly: true,
                buttonText: "Select date",
                maxDate: "+0D",
                dateFormat: "d-M-yy",
                changeMonth: true,
                changeYear: true
            });
        });

        self = this;

        user.UserProfiles = ko.observableArray(user.UserProfiles);

        for (var i = 0; i < user.UserProfiles().length; i++) {
            user.UserProfiles()[i].states = ko.observable([]);
        }

        self.user = ko.observable(user);

        self.prefixes = prefixes;
        //self.states = states;
        self.countries = countries;
        self.states = ko.observable([]);

        self.onCountryChange = function (obj, evt) {
            if (evt.target.value !== "") {
                var userProfileLocal = $linq(self.user().UserProfiles()).where('m=>m.Counter===' + obj.Counter).array[0];
                userProfileLocal.states($linq(self.countries).where('m=>m.CountryId===' + evt.target.value).array[0].States);
                //self.states($linq(self.countries).where('m=>m.CountryId===' + evt.target.value).array[0].States);
            }
        };

        self.addAddress = function () {
            var ctr = self.user().UserProfiles().length > 0 ? (parseInt($linq(self.user().UserProfiles()).max('m=>m.Counter'), 10) + 1) : 1;
            self.user().UserProfiles.push(
                {
                    "UserProfileId": 0,
                    "UserId": 0,
                    "Counter": ctr,
                    "Address1": "",
                    "Address2": "",
                    "City": "",
                    "Pincode": null,
                    "CountryId": null,
                    "StateId": null,
                    "MobileNo": null,
                    "PhoneNo": null,
                    "Email": "",
                    "Fax": null,
                    "Website": "",
                    "CreatedBy": 0,
                    "CreatedOn": null,
                    "EditedBy": 0,
                    "EditedOn": null,
                    "states": ko.observable([]),
                    "ApplStressOMeter": null
                }
            );
        }

        self.deleteAddress = function (address) {
            if (address && address.Counter) {
                if (self.user().UserProfiles().indexOf(address) > -1) {
                    self.user().UserProfiles.splice(self.user().UserProfiles().indexOf(address), 1);
                }
            }
        }

        var clone = function (objFrom, objTo) {
            for (var key in objFrom) {
                objTo[key] = ko.utils.unwrapObservable(objFrom[key]);

                if (objTo[key]) {
                    if (typeof (objTo[key]) === "object") {
                        if (objTo[key].length > 0) {
                            for (var i = 0; i < objTo[key].length; i++) {
                                clone(objTo[key][i], objTo[key][i]);
                            }
                        }
                        else {
                            clone(objTo[key], objTo[key]);
                        }
                    }
                }
            }
        }

        var ToJavaScriptDate = function (value) {
            var pattern = /Date\(([^)]+)\)/;
            var results = pattern.exec(value);
            var dt = new Date(parseFloat(results[1]));
            return dt.getDate() + "-" + (dt.getMonth() + 1) + "-" + dt.getFullYear();
        }

        var Validate = function (saveModel) {
            errorMessages = [];
            validationMessage = '';
            var isValid = true;

            for (var i = 0; i < saveModel.UserProfiles.length; i++) {
                if (saveModel.UserProfiles[i].MobileNo === null || saveModel.UserProfiles[i].MobileNo === undefined || saveModel.UserProfiles[i].MobileNo === "") {
                    validationMessage += 'Address' + saveModel.UserProfiles[i].Counter + (i === saveModel.UserProfiles.length - 1 ? '' : ', ');
                }
            }

            if (validationMessage != '') {
                errorMessages.push('Please enter Mobile Number for ' + validationMessage + '.');
                validationMessage = '';
                isValid = false;
            }

            for (var i = 0; i < saveModel.UserProfiles.length; i++) {
                if (saveModel.UserProfiles[i].Email === null || saveModel.UserProfiles[i].Email === undefined || saveModel.UserProfiles[i].Email === "") {
                    validationMessage += 'Address' + saveModel.UserProfiles[i].Counter + (i === saveModel.UserProfiles.length - 1 ? '' : ', ');
                }
            }

            if (validationMessage != '') {
                errorMessages.push('Please enter Email for ' + validationMessage + '.');
                validationMessage = '';
                isValid = false;
            }

            for (var i = 0; i < saveModel.UserProfiles.length; i++) {
                if (saveModel.UserProfiles[i].City === null || saveModel.UserProfiles[i].City === undefined || saveModel.UserProfiles[i].City === "") {
                    validationMessage += 'Address' + saveModel.UserProfiles[i].Counter + (i === saveModel.UserProfiles.length - 1 ? '' : ', ');
                }
            }

            if (validationMessage != '') {
                errorMessages.push('Please enter City for ' + validationMessage + '.');
                validationMessage = '';
                isValid = false;
            }

            if (!isValid) {
                for (var i = 0; i < errorMessages.length; i++) {
                    validationMessage += errorMessages[i] + '<br/>';
                }
            }

            return isValid;
        }

        self.save = function () {
            var url = '/Home/UserProfile';

            var saveModel = new Object();

            clone(self.user(), saveModel);

            saveModel.DateOfBirth = ToJavaScriptDate(saveModel.DateOfBirth);
            var isValid = Validate(saveModel);
            if (isValid) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(saveModel),
                    contentType: 'application/json',//; charset=utf-8',
                    dataType: 'json',
                    success: function (a, b, c) {
                        window.showToast('User Profile saved successfully.', 'User Profile', 1);
                        setTimeout(function () {
                            window.location = "../Home/Index";
                        }, 3000);
                    },
                    error: function (a, b, c) {
                        var test1 = '';
                    }
                });
            } else {
                window.showToast(validationMessage, 'User Profile', 4);
            }
        }
    }
    var viewModel = new UserProfileModel(data, prefixes, states, countries);
    ko.applyBindings(viewModel);
</script>
